package dbAdapter;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;


public class FoodDBAdapter {

	 public static final String KEY_CATEGORY = "category";
    public static final String KEY_NAME = "name";
    public static final String KEY_CALORIES = "calories";
    public static final String KEY_ROWID = "_id";
    public static final String KEY_QUANTITY = "quantity";
    public static final String KEY_FAT = "fat";    
    public static final String KEY_SATFAT = "saturatedFat";
    public static final String KEY_CHOLESTROL = "cholestrol";
    public static final String KEY_SODIUM = "sodium";
    public static final String KEY_CARBOHYDRATE = "carbohydrate";
    public static final String KEY_FIBER = "fiber";
    public static final String KEY_SUGAR = "sugar";
    public static final String KEY_VITA = "vitA";
    public static final String KEY_VITB = "vitB";
    public static final String KEY_VITC = "vitC";
    public static final String KEY_IRON = "iron";
    public static final String KEY_PROTEIN = "protein";  
    public static final String KEY_CALCIUM = "calcium";  
    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;

    /**
     * Database creation sql statement
     */
    // TODO: Change calories to int
    static final String CREATE_TABLE=
	     
    	"create table if not exists Food(" + KEY_ROWID + " integer primary key autoincrement, "
    	    + KEY_CATEGORY + " text not null,"
    		+ KEY_NAME + " text not null,"
            + KEY_QUANTITY + " text not null,"
            + KEY_CALORIES + " text,"
            + KEY_FAT  + " text,"
            + KEY_SATFAT + " text,"
            + KEY_CHOLESTROL + " text,"
            + KEY_SODIUM + " text,"
            + KEY_CARBOHYDRATE + " text,"
            + KEY_FIBER + " text,"
            + KEY_SUGAR + " text,"
            + KEY_PROTEIN + " text,"
            + KEY_VITA + " text,"
            + KEY_VITB + " text,"
            + KEY_VITC + " text,"
            + KEY_CALCIUM +" text,"
            + KEY_IRON + " text"
            +");";

//    "create table notes (_id integer primary key autoincrement, "
//    + "title text not null, body text not null);";

    private static final String DATABASE_TABLE = "Food";

    private final Context mCtx;

 

    /**
     * Constructor - takes the context to allow the database to be
     * opened/created
     * 
     * @param ctx the Context within which to work
     */
    public FoodDBAdapter(Context ctx) {
        this.mCtx = ctx;
    }

    /**
     * Open the notes database. If it cannot be opened, try to create a new
     * instance of the database. If it cannot be created, throw an exception to
     * signal the failure
     * 
     * @return this (self reference, allowing this to be chained in an
     *         initialization call)
     * @throws SQLException if the database could be neither opened or created
     */
    public FoodDBAdapter open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        mDbHelper.close();
    }


    /**
     * Create a new note using the title and body provided. If the note is
     * successfully created return the new rowId for that note, otherwise return
     * a -1 to indicate failure.
     * 
     * @param title the title of the note
     * @param body the body of the note
     * @return rowId or -1 if failed
     */
    
    public long insertFoodData(String category, String name,String quantity, String calories, String fat, String saturatedFat, String cholestrol,String sodium, String carbohydrate, String fiber, String sugar, String protein,String calcium, String vitA, String vitB, String vitC, String iron )
    { 
    	long result  = 0;
    	ContentValues initialValues = new ContentValues();
    		initialValues.put(KEY_CATEGORY, category);
	        initialValues.put(KEY_QUANTITY, quantity);
	        initialValues.put(KEY_CALORIES, calories);
	        initialValues.put(KEY_FAT, fat);
	        initialValues.put(KEY_SATFAT, saturatedFat);
	        initialValues.put(KEY_CHOLESTROL, cholestrol);
	        initialValues.put(KEY_SODIUM, sodium);
	        initialValues.put(KEY_CARBOHYDRATE, carbohydrate);
	        initialValues.put(KEY_FIBER, fiber);
	        initialValues.put(KEY_SUGAR, sugar);
	        initialValues.put(KEY_PROTEIN, protein);
	        initialValues.put(KEY_VITA, vitA);
	        initialValues.put(KEY_VITB, vitB);
	        initialValues.put(KEY_VITC, vitC);
	        initialValues.put(KEY_IRON, iron);
	        initialValues.put(KEY_CALCIUM, calcium);
	        initialValues.put(KEY_NAME, name);
	       System.out.println("Inside insert into DB: " + initialValues.get(calories));
	       try{
	        result =  mDb.insert("Food", null, initialValues);
	       } catch (Exception ex){
	    	   System.out.println("Exception in Food insert");
	       }
	       return result;
    	
    }

   
    /**
     * Return a Cursor over the list of all notes in the database
     * 
     * @return Cursor over all notes
     */
    public Cursor fetchAllNutrition() {

        return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME,
                KEY_QUANTITY,
                KEY_CALORIES,
                KEY_FAT,
                KEY_SATFAT,
                KEY_CHOLESTROL,
                KEY_SODIUM,
                KEY_CARBOHYDRATE,
                KEY_FIBER,
                KEY_SUGAR,
                KEY_PROTEIN,
                KEY_VITA,
                KEY_VITB,
                KEY_VITC,
                KEY_CALCIUM,
                KEY_IRON}, null, null, null, null, null);
    }

    public Cursor fetchNutrition(String name) {

        return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME,
        		KEY_CATEGORY,
        		KEY_QUANTITY,
                KEY_CALORIES,
                KEY_FAT,
                KEY_SATFAT,
                KEY_CHOLESTROL,
                KEY_SODIUM,
                KEY_CARBOHYDRATE,
                KEY_FIBER,
                KEY_SUGAR,
                KEY_PROTEIN,
                KEY_VITA,
                KEY_VITB,
                KEY_VITC,
                KEY_CALCIUM,
                KEY_IRON}, KEY_NAME + " = '" + name + "'", null, null, null, null);
    }
    
    public Cursor fetchNutritionWithLike(String name) {

        return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME,
        		KEY_CATEGORY,
        		KEY_QUANTITY,
                KEY_CALORIES,
                KEY_FAT,
                KEY_SATFAT,
                KEY_CHOLESTROL,
                KEY_SODIUM,
                KEY_CARBOHYDRATE,
                KEY_FIBER,
                KEY_SUGAR,
                KEY_PROTEIN,
                KEY_VITA,
                KEY_VITB,
                KEY_VITC,
                KEY_CALCIUM,
                KEY_IRON}, KEY_NAME + " LIKE '" + name + "%' OR " + KEY_NAME + " LIKE '" + name + " %' OR " + KEY_NAME + " LIKE '% " + name + "'" , null, null, null, null);
    }


    /**
     * Return a Cursor positioned at the note that matches the given rowId
     * 
     * @param rowId id of note to retrieve
     * @return Cursor positioned to matching note, if found
     * @throws SQLException if note could not be found/retrieved
     */
    public Cursor fetchNutrition(long rowId) throws SQLException {

        Cursor mCursor =

            mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
                    KEY_NAME, KEY_CALORIES}, KEY_ROWID + "=" + rowId, null,
                    null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;

    }

    /**
     * Update the note using the details provided. The note to be updated is
     * specified using the rowId, and it is altered to use the title and body
     * values passed in
     * 
     * @param rowId id of note to update
     * @param title value to set note title to
     * @param body value to set note body to
     * @return true if the note was successfully updated, false otherwise
     */
    public boolean updateNutrition(long rowId, String name, String calories) {
        ContentValues args = new ContentValues();
        args.put(KEY_NAME, name);
        args.put(KEY_CALORIES, calories);

        return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
    }
    
    public Cursor retrieveAllFoodNames(){
    	return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME},
                 null, null, null, null, null);
    	
    }
    

  /*  public String[] getCategoryList(String category) {
    	String catList[];
    	System.out.println("category is" +category);
    	System.out.println("Inside CategoryList");
		Cursor cursor =  mDb.rawQuery("select name from Food where category == ?", new String[]{getString(category)} );
		System.out.println("After calories burned");
		int i =0;
		try{
		if ( cursor.moveToFirst())
		{
			do {   
				System.out.println("Inside getCaloriesBurntForDay " +cursor.getInt(0));
			catList[i] =  cursor.getString(0);
			i ++;
			} while (cursor.moveToNext());
			return catList;
		}
		else
			return catList;
		} finally{
			cursor.close();
		}
		
	}*/
    
    public Cursor fetchCategoryItems(String category) {

        return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME},
        		 KEY_CATEGORY + " LIKE '%" + category + "%'", null, null, null, null);
    }
    
    public Cursor fetchCalories(String name) {

        return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_CALORIES},
        		 KEY_NAME + " LIKE '%" + name + "%'", null, null, null, null);
    }
    
    public String[] retrieveAllFoodNamesAsStringArray(){
        Cursor c = retrieveAllFoodNames();
        String[] foodNames = new String[c.getCount()];
                int i=0;
                while( c.moveToNext()){

                        foodNames[i] = c.getString(1);
                        i++;
                }
                c.close();
                return foodNames;
    }

}
